package com.sptus.web.controller.system;

import com.sptus.common.annotation.Anonymous;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import org.apache.poi.xwpf.usermodel.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/docx")
public class GenerateDocxController {

    @GetMapping("/export")
    @Anonymous
    public ResponseEntity<byte[]> exportDocx() {
        try {
            byte[] document = generateDocx();

            HttpHeaders headers = new HttpHeaders();
            headers.add("Content-Disposition", "attachment; filename=test01.docx");

            return new ResponseEntity<>(document, headers, HttpStatus.OK);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    public byte[] generateDocx() throws IOException {
        // Create the Word document
        try (XWPFDocument document = new XWPFDocument();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            // Add a title paragraph
            XWPFParagraph titleParagraph = document.createParagraph();
            titleParagraph.setAlignment(ParagraphAlignment.CENTER);
            XWPFRun titleRun = titleParagraph.createRun();
            titleRun.setText("This is a title");
            titleRun.setBold(true);
            titleRun.setFontSize(20);

            // Add a simple paragraph
            XWPFParagraph paragraph = document.createParagraph();
            paragraph.setAlignment(ParagraphAlignment.LEFT);
            XWPFRun paragraphRun = paragraph.createRun();
            paragraphRun.setText("This is a sample paragraph.");

            // Add a table
            XWPFTable table = document.createTable();
            XWPFTableRow tableRowOne = table.getRow(0);
            tableRowOne.getCell(0).setText("Header 1");
            tableRowOne.addNewTableCell().setText("Header 2");
            tableRowOne.addNewTableCell().setText("Header 3");

            XWPFTableRow tableRowTwo = table.createRow();
            tableRowTwo.getCell(0).setText("Row 1, Cell 1");
            tableRowTwo.getCell(1).setText("Row 1, Cell 2");
            tableRowTwo.getCell(2).setText("Row 1, Cell 3");

            document.write(outputStream);

            return outputStream.toByteArray();
        }
    }
}
